package com.zenithmind.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.chat.mapper.ChatGroupAssociationMapper;
import com.zenithmind.chat.pojo.entity.ChatGroupAssociation;
import com.zenithmind.chat.pojo.dto.ChatGroupAssociationDTO;
import com.zenithmind.chat.pojo.vo.ChatGroupAssociationVO;
import com.zenithmind.chat.service.ChatGroupAssociationService;
import com.zenithmind.common.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 群组关联服务实现 - 遵循单一职责原则
 * 只负责群组关联的业务逻辑处理
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatGroupAssociationServiceImpl extends ServiceImpl<ChatGroupAssociationMapper, ChatGroupAssociation> 
        implements ChatGroupAssociationService {

    private final ChatGroupAssociationMapper chatGroupAssociationMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createAssociation(ChatGroupAssociationDTO dto, String userId) {
        // 验证DTO
        if (!dto.isValid()) {
            throw new BusinessException("关联信息不完整");
        }

        // 检查关联是否已存在
        if (checkAssociationExists(dto.getGroupId(), dto.getAssociationType(), dto.getResourceId())) {
            throw new BusinessException("该关联已存在");
        }

        // 创建关联实体
        ChatGroupAssociation association = new ChatGroupAssociation();
        association.setGroupId(dto.getGroupId());
        // 需要将String转换为GroupType枚举
        // association.setAssociationType(GroupType.valueOf(dto.getAssociationType()));
        association.setResourceId(dto.getResourceId());
        association.setResourceName(dto.getResourceName());
        association.setResourceDescription(dto.getResourceDescription());
        association.setExtraInfo(dto.getExtraInfo());
        association.setStatus(1); // 默认有效状态
        association.setCreatorId(userId);

        // 保存关联
        save(association);
        
        log.info("创建群组关联成功，关联ID: {}, 操作人: {}", association.getId(), userId);
        return association.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteAssociation(String associationId, String userId) {
        ChatGroupAssociation association = getById(associationId);
        if (association == null) {
            throw new BusinessException("关联不存在");
        }

        // 软删除
        association.setUpdateBy(userId);
        association.setUpdateTime(LocalDateTime.now());
        boolean result = removeById(associationId);
        
        if (result) {
            log.info("删除群组关联成功，关联ID: {}, 操作人: {}", associationId, userId);
        }
        
        return result;
    }

    @Override
    public List<ChatGroupAssociationVO> getAssociationsByGroupId(String groupId, String userId) {
        List<ChatGroupAssociation> associations = chatGroupAssociationMapper.selectByGroupId(groupId);
        return associations.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<ChatGroupAssociationVO> getAssociationsByType(String associationType, String userId) {
        List<ChatGroupAssociation> associations = chatGroupAssociationMapper.selectByAssociationType(associationType);
        return associations.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<ChatGroupAssociationVO> getAssociationsByAssociationId(String associationId, String userId) {
        List<ChatGroupAssociation> associations = chatGroupAssociationMapper.selectByAssociationId(associationId);
        return associations.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public Boolean checkAssociationExists(String groupId, String associationType, String associationId) {
        int count = chatGroupAssociationMapper.checkAssociationExists(groupId, associationType, associationId);
        return count > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchCreateAssociations(List<ChatGroupAssociationDTO> dtoList, String userId) {
        if (CollectionUtils.isEmpty(dtoList)) {
            return true;
        }

        List<ChatGroupAssociation> associations = dtoList.stream()
                .filter(ChatGroupAssociationDTO::isValid)
                .map(dto -> {
                    ChatGroupAssociation association = new ChatGroupAssociation();
                    association.setGroupId(dto.getGroupId());
                    // association.setAssociationType(GroupType.valueOf(dto.getAssociationType()));
                    association.setResourceId(dto.getResourceId());
                    association.setResourceName(dto.getResourceName());
                    association.setResourceDescription(dto.getResourceDescription());
                    association.setExtraInfo(dto.getExtraInfo());
                    association.setStatus(1);
                    association.setCreatorId(userId);
                    return association;
                })
                .collect(Collectors.toList());

        boolean result = saveBatch(associations);
        
        if (result) {
            log.info("批量创建群组关联成功，数量: {}, 操作人: {}", associations.size(), userId);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchDeleteAssociations(List<String> associationIds, String userId) {
        if (CollectionUtils.isEmpty(associationIds)) {
            return true;
        }

        boolean result = removeByIds(associationIds);
        
        if (result) {
            log.info("批量删除群组关联成功，数量: {}, 操作人: {}", associationIds.size(), userId);
        }
        
        return result;
    }

    /**
     * 转换为VO对象 - 遵循单一职责原则
     */
    private ChatGroupAssociationVO convertToVO(ChatGroupAssociation association) {
        ChatGroupAssociationVO vo = new ChatGroupAssociationVO();
        vo.setId(association.getId());
        vo.setGroupId(association.getGroupId());
        vo.setAssociationType(association.getAssociationType() != null ? association.getAssociationType().name() : null);
        vo.setResourceId(association.getResourceId());
        vo.setResourceName(association.getResourceName());
        vo.setResourceDescription(association.getResourceDescription());
        vo.setExtraInfo(association.getExtraInfo());
        vo.setStatus(association.getStatus());
        vo.setCreatorId(association.getCreatorId());
        vo.setCreateTime(association.getCreateTime());
        vo.setUpdateTime(association.getUpdateTime());
        vo.setCreateBy(association.getCreateBy());
        vo.setUpdateBy(association.getUpdateBy());
        return vo;
    }
}
